package com.banach.prema.im.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.banach.prema.constant.MsgType;
import com.banach.prema.dto.cmd.AlarmAdd;
import com.banach.prema.dto.vo.ContactVO;
import com.banach.prema.im.config.AppConfig;
import com.banach.prema.im.util.RestApiUtils;
import com.banach.prema.im.util.CommonUtils;
import com.banach.prema.repository.ContactRepository;
import com.banach.prema.repository.GroupRepository;
import com.banach.prema.repository.dataobject.GroupDO;
import com.banach.prema.repository.dataobject.TempMemberDO;
import com.ego.framework.core.context.UserHolder;
import com.ego.framework.core.util.Md5Utils;
import com.ego.framework.core.util.Snowflake;
import com.ego.framework.model.LoginUser;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GroupRestApi {
	@Resource
	private ContactRepository contactRepository;
	@Resource
	private RestApiUtils restApiUtil;
	@Resource
	private GroupRepository groupRepository;
	@Resource
	private AppConfig appConfig;

	@Resource
	private Snowflake snowflake;



	
	/**
	 * 创建风险预警大聊天室
	 * @param alarm
	 * @return 
	 */
	public String createAlarmGroup(AlarmAdd alarm){
		LoginUser loginUser = UserHolder.getLoginUser();
		GroupDO query = new GroupDO();
		query.setCode(String.valueOf(alarm.getId()));
		query.setOwnerAccount(loginUser.getMobile());
		query.setValid(true);
		GroupDO group = groupRepository.selectOne(query);

		if(group!=null){
			return group.getId();
		}
		JSONObject data = new JSONObject();
		data.put("GroupId", snowflake.nextId());
		data.put("Name", alarm.getTitle());
		data.put("Type", "BhatRoom");//ChatRoom
		data.put("FaceUrl", appConfig.getUrl()+"/images/im/alarm.jpg");
		data.put("ApplyJoinOption", "FreeAccess");
		data.put("OwnerAccount", loginUser.getMobile());
		JSONObject res = restApiUtil.doPost("/v4/group_open_http_svc/create_group", data);
		if("OK".equals(res.get("ActionStatus"))){
			String groupId = res.getString("GroupId");
			group = new GroupDO();
			group.setId(groupId);
			group.setName(alarm.getTitle());
			group.setCode(String.valueOf(alarm.getId()));
			group.setType("BChatRoom");//ChatRoom
			group.setOwnerAccount(loginUser.getMobile());
			group.setOperatorAccount(appConfig.getIdentifier());
			groupRepository.save(group);
			return groupId;
		}
		return null;
	}


	/**
	 * 创建求救讨论群
	 * @param user
	 * @return
	 */
	public String createMyGroup(LoginUser user,String type,String mobiles){
		final JSONArray memberList = new JSONArray();
		List<ContactVO> contacts = contactRepository.selectByUserId(user.getId());

		JSONObject member1 = new JSONObject();
		member1.put("MemberAccount", user.getMobile());
		memberList.add(member1);

		for(String mobile : mobiles.replace(",", ";").split(";")){
			JSONObject member = new JSONObject();
			member.put("MemberAccount", mobile);
			memberList.add(member);
		}
		String groupId = snowflake.nextId().toString();
		JSONObject data = new JSONObject();
		data.put("GroupId", groupId);
		data.put("Name", user.getName()+"新建群("+memberList.size()+")");
		data.put("Type", type);
		data.put("FaceUrl", appConfig.getUrl()+"/images/im/group.jpg");
		data.put("OwnerAccount", user.getMobile());
		data.put("MemberList", memberList);
		JSONObject res = restApiUtil.doPost("/v4/group_open_http_svc/create_group", data);
		if("OK".equals(res.get("ActionStatus"))){
			JSONArray msgBody = new JSONArray();
			JSONObject textMsg = new JSONObject();
			textMsg.put("MsgType", MsgType.TEXT);
			JSONObject msgContent = new JSONObject();
			msgContent.put("Text", "大家好！");
			textMsg.put("MsgContent", msgContent);
			msgBody.add(textMsg);
			sendMsg(user.getMobile(), groupId, msgBody, null);

			GroupDO group = new GroupDO();
			group.setId(groupId);
			group.setName(user.getName()+"新建群");
			group.setMemberList(memberList.toJSONString());
			group.setType(type);
			group.setOwnerAccount(user.getMobile());
			group.setOperatorAccount(appConfig.getIdentifier());
			List<TempMemberDO> tempMembers = new ArrayList<TempMemberDO>();
			for(String mobile : mobiles.replace(",", ";").split(";")){
				tempMembers.add(new TempMemberDO(groupId, mobile));
			}
			return groupId;
		}
		return null;
	}


	/**
	 * 创建求救讨论群
	 * @param groupId
	 * @return
	 */
	public JSONObject modifyGroupFaceUrl(String groupId,String faceUrl){
		JSONObject data = new JSONObject();
		data.put("GroupId", groupId);
		data.put("FaceUrl",faceUrl);
		JSONObject res = restApiUtil.doPost("/v4/group_open_http_svc/modify_group_base_info", data);
		return res;
	}


	/**
	 * 创建求救讨论群
	 * @param user
	 * @return
	 */
	public String createSosGroup(LoginUser user){

		List<ContactVO> contacts = contactRepository.selectByUserId(user.getId());

		List mobiles = contacts.stream().map(x->x.getMobile()).sorted().collect(Collectors.toList());
		final String code = Md5Utils.md5(JSON.toJSONString(mobiles));
		GroupDO group = groupRepository.selectByOwnerAndCode(user.getMobile(),code);
		if(group!=null){
			return group.getId();
		}
		final JSONArray memberList = new JSONArray();
		for(ContactVO contact : contacts){
			JSONObject member = new JSONObject();
			member.put("Member_Account", contact.getMobile());
			memberList.add(member);
		}
		String groupId = snowflake.nextId().toString();
		JSONObject data = new JSONObject();
		data.put("GroupId", groupId);
		data.put("Name", user.getName()+"-求救");
		data.put("Type", "ChatRoom");
		data.put("FaceUrl", appConfig.getUrl()+"/images/im/sos.jpg");
		data.put("Owner_Account", user.getMobile());
		data.put("MemberList", memberList);
		JSONObject res = restApiUtil.doPost("/v4/group_open_http_svc/create_group", data);
		if("OK".equals(res.get("ActionStatus"))){
			group = new GroupDO();
			group.setId(groupId);
			group.setName(user.getName()+"-求救");
			group.setCode(code);
			group.setMemberList(memberList.toJSONString());
			group.setType("Public");
			group.setOwnerAccount(user.getMobile());
			group.setOperatorAccount(appConfig.getIdentifier());

			List<TempMemberDO> tempMembers = new ArrayList<TempMemberDO>();
			for(ContactVO contact : contacts){
				tempMembers.add(new TempMemberDO(groupId, contact.getMobile()));
			}
			groupRepository.create(group);
			return groupId;
		}
		return null;
	}


	/**
	 * 发送单条消息
	 * @param sender
	 * @param groupId
	 * @param msg
	 * @return
	 */
	public boolean sendMsg(String sender,String groupId,JSONObject msg,JSONObject offlinePushInfo){
		JSONArray msgBody = new JSONArray();
		msgBody.add(msg);
		return sendMsg(sender, groupId, msgBody,offlinePushInfo);
	}

	/**
	 * 发送多条消息
	 * @param sender
	 * @param groupId
	 * @param msgBody
	 * @return
	 */
	public boolean sendMsg(String sender,String groupId,JSONArray msgBody,JSONObject offlinePushInfo){
		JSONObject data = new JSONObject();
		data.put("GroupId", groupId);
		data.put("Random", CommonUtils.getRdm(8));
		data.put("FromAccount", sender);
		data.put("MsgBody", msgBody);
		if(offlinePushInfo!=null){
			data.put("OfflinePushInfo", offlinePushInfo);
		}
		JSONObject res = restApiUtil.doPost("/v4/group_open_http_svc/send_group_msg", data);
		return "OK".equals(res.get("ActionStatus"));
	}
	
	public boolean sendSysMsg(String groupId,String content){
		JSONObject data = new JSONObject();
		data.put("GroupId", groupId);
		data.put("Content", content);
		JSONObject res = restApiUtil.doPost("/v4/group_open_http_svc/send_group_system_notification", data);
		return "OK".equals(res.get("ActionStatus"));
	}
	
	
	public boolean updateGroupName(String groupId,String name){
		JSONObject data = new JSONObject();
		data.put("GroupId", groupId);
		data.put("Name", name);
		JSONObject res = restApiUtil.doPost("/v4/group_open_http_svc/modify_group_base_info", data);
		return "OK".equals(res.get("ActionStatus"));
	}
	
	
	
	/**
	 * 解散群组
	 * @param groupId
	 * @return
	 */
	public boolean destroyGroup(String groupId){
		JSONObject data = new JSONObject();
		data.put("GroupId", groupId);
		JSONObject res = restApiUtil.doPost("v4/group_open_http_svc/destroy_group", data);
		return "OK".equals(res.get("ActionStatus"))||"10010".equals(res.getString("ErrorCode"));
	}
	
	
	/**
	 * 撤回消息
	 * @param groupId
	 * @param msgSeq
	 * @return
	 */
	public boolean recallMsg(String groupId,Integer msgSeq){
		List<Integer> msgSeqs = new ArrayList<Integer>();
		msgSeqs.add(msgSeq);
		return recallMsg(groupId, msgSeq);
	}
	/**
	 * 撤回多条消息
	 * @param groupId
	 * @param msgSeqs
	 * @return
	 */
	public boolean recallMsg(String groupId,List<Integer> msgSeqs){
		JSONArray msgSeqList = new JSONArray();
		for(Integer msgSeq : msgSeqs){
			JSONObject msg = new JSONObject();
			msg.put("MsgSeq", msgSeq);
			msgSeqList.add(msg);
		}
		return recallMsg(groupId, msgSeqList);
	}
	
	/**
	 * 撤回多条消息
	 * @param groupId
	 * @param msgSeqList
	 * @return
	 */
	public boolean recallMsg(String groupId,JSONArray msgSeqList){
		JSONObject data = new JSONObject();
		data.put("GroupId", groupId);
		data.put("MsgSeqList", msgSeqList);
		JSONObject res = restApiUtil.doPost("/v4/group_open_http_svc/group_msg_recall", data);
		return "OK".equals(res.get("ActionStatus"));
	}

}
